package com.ss.mq.util;

import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Properties;

/**
 * @author 叁昇
 * @create 2020-12-10-18:40
 */
public class RabbitUtils {
    private static final Logger logger = LoggerFactory.getLogger(RabbitUtils.class);

    private static ConnectionFactory factory = new ConnectionFactory();

    static {
        // 获取配置文件信息
        Properties properties = new Properties();
        try {
            properties.load(RabbitUtils.class.getClassLoader().getResourceAsStream("rabbitConfig.properties"));
        } catch (IOException e) {
            logger.error("读取配置文件失败!");
            e.printStackTrace();
        }

        String host = properties.getProperty("rabbit.host");
        String port = properties.getProperty("rabbit.port");
        String username = properties.getProperty("rabbit.username");
        String password = properties.getProperty("rabbit.password");

        // 设置连接信息
        factory.setHost(host);
        factory.setPort(Integer.parseInt(port));
        factory.setUsername(username);
        factory.setPassword(password);
    }

    public static Connection getConnection() {
        Connection connection;
        try {
            /*
              与 mq 服务器建立连接,
              rabbitMQ 使用 nio, 会复用 tcp 连接,
              并开辟多个信道与客户端通信, 以减轻服务端建立连接的开销
             */
            connection = factory.newConnection();
            return connection;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
